package net.shambolica.ember.jinterface.wrappers.objects.patterns;

import com.ericsson.otp.erlang.OtpErlangAtom;
import com.ericsson.otp.erlang.OtpErlangObject;
import net.shambolica.ember.jinterface.wrappers.objects.EOPattern;

import java.util.HashMap;
import java.util.Map;

import static net.shambolica.ember.utils.StringUtils.isEmpty;

/**
 * A pattern which assigns a value to the var map.
 * Matching will fail if the variable already exists, with a different value.
 */
public class EOPVar extends EOPattern {

    private final String varName;

    public EOPVar(String varName) {
        if (isEmpty(varName)) {
            throw new IllegalArgumentException("empty var name in pattern");
        }
        this.varName = varName;
    }

    public String getVarName() {
        return varName;
    }

    @Override
    public Map<String, OtpErlangObject> match(OtpErlangObject term, Map<String, OtpErlangObject> acc) {
        if (acc.containsKey(varName)) {
            return term.equals(acc.get(varName)) ? acc : null;
        } else {
            Map<String,OtpErlangObject> ret = new HashMap<String, OtpErlangObject>(acc);
            ret.put(varName, term);
            return ret;
        }
    }

    @Override
    public OtpErlangObject instantiate() {
        return null;
    }

    @Override
    public boolean isAbstract() {
        return true;
    }

}